<template>
  <div class="wrap">
    <div class="header">
      <div class="back" @click="back">
        <a-icon type="left"></a-icon>
      </div>
      <span>{{ mode === "create" ? "新增" : "" }}申报{{ mode === "edit" ? "详情" : "" }}</span>
    </div>
    <a-spin :spinning="spinning" class="main">
      <div class="info">
        <div>
          <div class="name">
            <a-switch v-model="isPrecedence" :disabled="!isEditing" size="small" />
            <span>是否优先</span>
          </div>
          <div v-if="mode === 'create'" class="detail">
            <div class="item"><span>接单时间：</span>{{ initValues.takeOrdersDate }}</div>
            <div class="item"><span>接单客服：</span>{{ initValues.takeOrdersUserName }}</div>
            <div class="item"><span>所属用工单位：</span>{{ initValues.companyName }}</div>
          </div>
          <div v-if="mode === 'edit' && tempInfo" class="detail">
            <div class="item"><span>接单时间：</span>{{ formatDate(tempInfo.takeOrdersDate) }}</div>
            <div class="item"><span>接单客服：</span>{{ tempInfo.takeOrdersUserName }}</div>
            <div class="item"><span>所属用工单位：</span>{{ tempInfo.companyName }}</div>
          </div>
        </div>
        <a-space v-if="mode !== 'create'">
          <a-button v-if="mode === 'edit' && isFinish" @click="handleEventFinish">恢复为未完结</a-button>
          <a-button v-if="mode === 'edit' && !isFinish && !isEditing" @click="handleEventFinish">事件完结</a-button>
          <a-button
            v-if="permissions_dycl.includes('dycl:dycl.dyclList:update') && isEditing === false && !isFinish"
            type="primary"
            @click="isEditing = true"
            >编辑</a-button
          >
        </a-space>
      </div>
      <div class="content">
        <div class="box">
          <div class="title">员工信息</div>
          <div v-if="mode !== 'create'" class="empinfo">
            <FieldForm
              v-if="empFields && empFields.length > 0"
              ref="empInfo"
              :isEmpInfo="true"
              :fieldList="empFields"
              :editable="isEditing"
              :isDetail="true"
            />
          </div>
          <template v-if="mode === 'create' && empInfo">
            <a-button @click="selectStart">重新选择</a-button>
            <div class="empinfo">
              <FieldForm
                v-if="empFields && empFields.length > 0"
                ref="empInfo"
                :isEmpInfo="true"
                :fieldList="empFields"
                :editable="isEditing"
                :dataSource="empInfo"
              />
            </div>
          </template>
          <a-button v-else-if="mode === 'create'" style="margin-bottom: 24px" @click="selectStart">选择员工</a-button>
          <div class="title">事件概况</div>
          <FieldForm
            v-if="eventFields && eventFields.length > 0"
            ref="eventInfo"
            :fieldList="eventFields"
            :editable="isEditing"
            :isDetail="mode !== 'create'"
          />
        </div>
        <div class="line"></div>
        <div class="box">
          <div class="title">处理过程</div>
          <div class="mb24">
            <span class="mr12">目前流程</span>
            <a-select
              v-model="currentWorkflow"
              :options="workflowLst"
              :disabled="!isEditing"
              allowClear
              placeholder="请选择"
              style="width: 200px"
            />
          </div>
          <div v-for="(li, idx) in processes" :key="`${li.name}_${idx}`" class="process" :class="{ first: idx === 0 }">
            <div class="pTitle">{{ idx + 1 }} {{ li.name }}</div>
            <div class="pBox">
              <FieldForm
                v-if="li.fields && li.fields.length > 0"
                :ref="`processInfo_${idx}`"
                :fieldList="li.fields"
                :editable="isEditing"
                :isDetail="mode !== 'create'"
              />
            </div>
          </div>
        </div>
      </div>
    </a-spin>
    <div v-if="isEditing" class="footer">
      <a-button :disabled="spinning" type="primary" @click="save">保存</a-button>
    </div>
    <a-modal v-model="selectModalVisible" title="选择员工" @ok="selectOk">
      <a-select
        v-if="empLst && empLst.length > 0"
        :defaultValue="defaultSelectValue"
        :options="empLst"
        :filterOption="filterOption"
        placeholder="员工姓名/身份证号/手机号"
        showSearch
        style="width: 100%"
        @change="selectChange"
      />
      <a-empty v-else description="正在加载员工..." class="empty">
        <a-icon slot="image" type="loading" style="font-size: 20px"></a-icon>
      </a-empty>
    </a-modal>
  </div>
</template>
<script>
import { detailTemplateReq } from "./templates/api";
import {
  selectByCompanyIdReq,
  createTreatmentDisposeEventsReq,
  updateTreatmentDisposeEventsReq,
  selectProcessChildByTemplateIdReq,
  selectEventInfoByIdReq,
  finishOrUnfinishedEventReq
} from "./api";
import FieldForm from "./components/fieldForm";
import { formatDate } from "./components/funcs";
import { mapGetters } from "vuex";
export default {
  inject: ["reload"],
  components: { FieldForm },
  mixins: [],
  props: {},
  data() {
    return {
      spinning: false,
      isEditing: false,
      isPrecedence: false,
      isFinish: false,
      workflowLst: [],
      currentWorkflow: undefined,
      tempInfo: null,
      empInfoTemp: null,
      empLst: [],
      selectModalVisible: false,
      empInfo: null,
      initValues: {},
      empData: null,
      empFormJson: {},
      eventData: null,
      eventFormJSon: {},
      empFields: [],
      eventFields: [],
      processes: []
    };
  },
  computed: {
    ...mapGetters(["permissions_dycl"]),
    mode() {
      if (this.$route.path === "/daiyuchuli/add") {
        return "create";
      } else if (this.$route.params.id) {
        return "edit";
      }
      return "other";
    },
    defaultSelectValue() {
      return this.empInfo ? this.empInfo.id : undefined;
    }
  },
  watch: {
    mode: {
      handler(newVal) {
        if (newVal === "create") {
          this.isEditing = true;
        }
      },
      immediate: true
    }
  },
  created() {
    if (this.mode === "create") {
      this.initCreate();
    } else if (this.mode === "edit") {
      this.initEdit();
    }
  },
  mounted() {},
  methods: {
    formatDate,
    handleEventFinish() {
      finishOrUnfinishedEventReq(this.$route.params.id, !this.isFinish)
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success(res.msg);
            this.reload();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    async save() {
      if (!this.$refs.empInfo) {
        this.$message.warning("请选择员工");
      } else {
        const nodes = Object.keys(this.$refs).map((key) => (key.indexOf("processInfo_") > -1 ? this.$refs[key][0] : this.$refs[key]));
        let values = [];
        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i];
          const valLst = await node.getValues();
          if (valLst) {
            values = values.concat(valLst);
          } else {
            return false;
          }
        }
        this.spinning = true;
        const valueMap = {};
        for (let i = 0; i < values.length; i++) {
          const valItem = values[i];
          if (valItem.fieldCode) {
            valueMap[valItem.fieldCode] = valItem.content;
          }
        }
        let obj = null;
        if (this.mode === "create") {
          obj = {
            ...this.initValues,
            eventType: this.tempInfo.eventType,
            empId: this.empInfo.id,
            empName: valueMap.name,
            empIdCard: valueMap.idCard,
            workCity: valueMap.workCity,
            currentWorkflow: this.currentWorkflow,
            isFinish: this.isFinish,
            isPrecedence: this.isPrecedence,
            fieldValueList: values
          };
        } else {
          obj = {
            ...this.tempInfo,
            empName: valueMap.name,
            empIdCard: valueMap.idCard,
            workCity: valueMap.workCity,
            currentWorkflow: this.currentWorkflow,
            isFinish: this.isFinish,
            isPrecedence: this.isPrecedence,
            fieldValueList: values
          };
        }
        const func = this.mode === "create" ? createTreatmentDisposeEventsReq : updateTreatmentDisposeEventsReq;
        func(obj)
          .then((res) => {
            this.spinning = false;
            if (res && res.data) {
              this.$message.success("保存成功");
              this.$router.push({
                path: "/daiyuchuli/list"
              });
            } else {
              this.$message.error("保存失败");
            }
          })
          .catch((err) => {
            this.spinning = false;
            console.log(err);
          });
      }
    },
    selectOk() {
      this.empInfo = this.empInfoTemp;
      this.selectModalVisible = false;
    },
    selectChange(value, node) {
      this.empInfoTemp = node.data.props.item;
    },
    selectStart() {
      if (!this.empLst.length) {
        selectByCompanyIdReq(this.initValues.companyId)
          .then((res) => {
            if (res && res.data) {
              this.empLst = res.data.map((item) => ({
                value: item.id,
                label: `${item.name} (${item.idCard})`,
                item
              }));
            } else {
              this.empLst = [];
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
      this.selectModalVisible = true;
    },
    filterOption(input, option) {
      const item = option.data.props.item;
      const text = (item.name || "") + (item.idCard || "") + (item.phone || "");
      return text.indexOf(input.toLowerCase()) >= 0;
    },
    initEdit() {
      selectEventInfoByIdReq(this.$route.params.id)
        .then((res) => {
          if (res && res.data) {
            this.tempInfo = res.data;
            this.isFinish = res.data.isFinish;
            this.isPrecedence = res.data.isPrecedence;
            this.currentWorkflow = res.data.currentWorkflow;
            this.loadTempProcesses(res.data.templateId);

            this.empFields = res.data.formGroupTree[0].formGroupFieldList;
            this.eventFields = res.data.formGroupTree[1].formGroupFieldList;
            this.processes = res.data.formGroupTree[2].childList.map((item) => ({
              name: item.moduleName,
              fields: item.formGroupFieldList
            }));
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    initCreate() {
      this.initValues = JSON.parse(localStorage.getItem("addDaiyuchuliItem"));
      this.loadTempProcesses(this.initValues.templateId);
      this.isFinish = this.initValues.isFinish;
      this.isPrecedence = this.initValues.isPrecedence;

      // 加载模板
      detailTemplateReq(this.initValues.templateId)
        .then((res) => {
          if (res && res.data) {
            this.tempInfo = res.data;
            this.empFields = res.data.formGroupTree[0].formGroupFieldList;
            this.eventFields = res.data.formGroupTree[1].formGroupFieldList;
            this.processes = res.data.formGroupTree[2].childList.map((item) => ({
              name: item.moduleName,
              fields: item.formGroupFieldList
            }));
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    loadTempProcesses(tempId) {
      selectProcessChildByTemplateIdReq(tempId)
        .then((res) => {
          if (res && res.data) {
            this.workflowLst = res.data.map((item) => ({
              value: item.moduleName,
              label: item.moduleName
            }));
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    back() {
      this.$router.go(-1);
    }
  }
};
</script>
<style lang="scss" scoped>
.wrap {
  background: #fff;
  border-radius: 4px;
  .header {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60px;
    line-height: 60px;
    box-shadow: inset 0px -1px 0px 0px #e8e8e8;
    position: relative;
    font-size: 16px;
    font-weight: 500;
    .back {
      position: absolute;
      top: 0;
      left: 0;
      width: 60px;
      height: 60px;
      cursor: pointer;
      text-align: center;
      font-size: 18px;
    }
  }
}
.main {
  padding: 24px;
  padding-bottom: 53px;
  .content {
    display: flex;
    margin-top: 24px;
    min-height: calc(100vh - 344px);
    .box {
      flex: 1;
      ::v-deep .ant-form-item {
        margin-bottom: 8px;
      }
    }
    .line {
      flex-shrink: 0;
      height: 100%;
      width: 1px;
      background: #e8e8e8;
      margin: 0 24px;
    }
  }
}
.info {
  height: 80px;
  background: #ffffff;
  box-shadow: 0px 4px 12px 0px rgba(106, 102, 246, 0.1);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px;
  .name {
    display: flex;
    align-items: center;
    color: rgba(118, 120, 133, 1);
    span {
      margin-left: 8px;
    }
  }
  .detail {
    margin-top: 12px;
    display: flex;
    align-items: center;
    .item {
      margin-right: 24px;
      span {
        color: rgba(166, 168, 180, 1);
      }
    }
  }
}
.title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  font-weight: 500;
  border-left: 3px solid var(--primary);
  padding-left: 12px;
  margin-bottom: 24px;
}
.process {
  border-left: 1px solid rgba(232, 232, 232, 1);
  padding: 12px 16px;
  position: relative;
  &.first {
    margin-top: -12px;
    &::after {
      position: absolute;
      content: "";
      left: -1px;
      top: 0;
      height: 20px;
      width: 2px;
      background: #fff;
      z-index: 1;
    }
  }
  &.end {
    padding-bottom: 24px;
  }
}
.pTitle {
  margin-bottom: 16px;
  color: rgba(85, 86, 93, 1);
  font-size: 16px;
  &::after {
    position: absolute;
    content: "";
    height: 10px;
    width: 10px;
    border-radius: 50%;
    background: var(--primary);
    top: 20px;
    left: -6px;
    z-index: 2;
  }
  ::v-deep .anticon {
    color: var(--primary);
    cursor: pointer;
  }
}
.pBox {
  background: #f9f9f9;
  border-radius: 4px;
  padding: 12px;
}
.footer {
  bottom: 0;
  left: 182px;
  right: 0;
  height: 53px;
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  background: #fff;
  box-shadow: 0px -1px 6px 0px rgba(0, 0, 0, 0.12);
  z-index: 10;
}
.empinfo {
  background: #ffffff;
  box-shadow: 0px 4px 12px 0px rgba(106, 102, 246, 0.1);
  border-radius: 4px;
  padding: 0 12px;
  margin: 24px 0;
}
.empty {
  ::v-deep .ant-empty-image {
    height: auto;
  }
}
</style>
